package com.jie.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jie.dao.BlogATagMapper;
import com.jie.dao.BlogMapper;
import com.jie.dao.TypeMapper;
import com.jie.pojo.*;
import com.jie.service.BlogService;
import com.jie.service.TagsService;
import com.jie.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 曾豪杰
 * @Date: 2022/09/12/10:39
 * @Description:
 */
@Controller
@Slf4j
@RequestMapping("/admin")
public class BlogController {


    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagsService tagsService;
    @Autowired
    private BlogATagMapper blogATagMapper;
//    @Autowired
//    private TypeMapper typeMapper;
    @Autowired
    private BlogMapper blogMapper;

    @GetMapping("/blog")
    public String getBlog(Blog blog, @RequestParam(defaultValue = "1",value = "page") int page,
                          @RequestParam(defaultValue = "8",value = "pageSize") Integer pageSize,
                          Model model){
        if(blog.getTitle()==null|| Objects.equals(blog.getTitle(), "")){
            blog.setTitle(null);
        }
        if(blog.getType()==null|| Objects.equals(blog.getType(), "")|| Objects.equals(blog.getType(), "无")){
            blog.setType(null);
        }
//        System.out.println("------");
//        System.out.println(blog.toString());
//        System.out.println("------");
        //构造分页
        Page<Blog> pageInfo =new Page<>(page,pageSize);
        LambdaQueryWrapper<Blog> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(blog.getTitle()!=null,Blog::getTitle,blog.getTitle());
        if(blog.getType()!=null){
            LambdaQueryWrapper<Type> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Type::getName,blog.getType());
            queryWrapper.like(blog.getType()!=null,Blog::getType,typeService.getOne(lambdaQueryWrapper).getId());
        }
        queryWrapper.eq(blog.getRecommend()== 1L||blog.getRecommend()== 2L,Blog::getRecommend,blog.getRecommend());
        queryWrapper.orderByDesc(Blog::getUpdateTime);
        Page<Blog> pages = blogService.page(pageInfo,queryWrapper);
        for (Blog record : pages.getRecords()) {
            Type type=new Type();
            type.setId(Long.valueOf(record.getType()));
            type.setName(typeService.getById(record.getType()).getName());
            record.setTypes(type);
        }
        model.addAttribute("typeInfo",typeService.list());
        model.addAttribute("page",pages);
//        System.out.println("------");
//        System.out.println(pages.getRecords().toString());
//        System.out.println("------");
        return "admin/blogs";
    }
    @GetMapping("/input")
    public String input(Model model){
        Blog blog=new Blog();
        blog.setRecommend(1);
        model.addAttribute("blog",blog);
        model.addAttribute("types",typeService.list());
        model.addAttribute("tags",tagsService.list());
        return "admin/blogs-input";
    }
    // 包含字母
    private static String CONTAIN_LETTER_REGEX = ".*[a-zA-z].*";
    // 纯中文
    private static String CHINESE_REGEX = "[\u4e00-\u9fa5]";
    // 含有数字
    private static String CONTAIN_DIGIT_REGEX = ".*[0-9].*";

    @Transactional
    @PostMapping("/blogs")
    public String post(Blog blog, HttpSession session, RedirectAttributes redirectAttributes){
        blog.setUser((User) session.getAttribute("user"));
        blog.setViews(0);
        blog.setType(String.valueOf(typeService.getById(blog.getTypes().getId()).getId()));
        List<Long> list=new ArrayList<>();
        String[] idArray=blog.getTagIds().split(",");
        for (String s : idArray) {
            Tag one1 = tagsService.getOne(new LambdaQueryWrapper<Tag>().orderByDesc(Tag::getId).last("limit 1"));
            //id值进行比较
            if(s.matches(CONTAIN_LETTER_REGEX)||s.matches(CHINESE_REGEX)){
                LambdaQueryWrapper<Tag> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(Tag::getName,s);
                Tag one = tagsService.getOne(queryWrapper);
                if(one==null){
                    Tag tag=new Tag();
                    tag.setName(s);
                    tagsService.save(tag);
                    Long id = tag.getId();
                    list.add(id);
                }else {
                    list.add(new Long(s));
                }
            }else {
                long l = Long.parseLong(s);
                if(l>one1.getId()){
                    LambdaQueryWrapper<Tag> queryWrapper=new LambdaQueryWrapper<>();
                    queryWrapper.eq(Tag::getName,s);
                    Tag one = tagsService.getOne(queryWrapper);
                    if(one==null){
                        Tag tag=new Tag();
                        tag.setName(s);
                        tagsService.save(tag);
                        Long id = tag.getId();
                        list.add(id);
                    }else {
                        list.add(new Long(s));
                    }
                }
                list.add(new Long(s));
            }
        }
        blog.setTagList(tagsService.listByIds(list));
        boolean save = blogService.saveOrUpdate(blog);
        if(save){
            //delete-save 中间表
            Long id12 = blog.getId();
            LambdaQueryWrapper<Blog_Tag> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Blog_Tag::getBId,id12);
            blogATagMapper.delete(lambdaQueryWrapper);
            for (Tag tag : blog.getTagList()) {
                Long id = tag.getId();
                Long id1 = blog.getId();
                LambdaQueryWrapper<Blog_Tag> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(Blog_Tag::getBId,id1);
                queryWrapper.eq(Blog_Tag::getTId,id);
                Blog_Tag blog_tag=new Blog_Tag();
                blog_tag.setBId(id1);
                blog_tag.setTId(id);
                blogATagMapper.insert(blog_tag);
            }

            redirectAttributes.addFlashAttribute("message","操作成功");
        }else {
            redirectAttributes.addFlashAttribute("message","操作失败");
        }
        return "redirect:/admin/blog";
    }


    @GetMapping("/edit/input")
    public String editInput(Long id, Model model){
        model.addAttribute("types",typeService.list());
        model.addAttribute("tags",tagsService.list());


        Blog byId = blogMapper.selectById(id);
        LambdaQueryWrapper<Blog_Tag> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog_Tag::getBId,byId.getId());
        List<Blog_Tag> blogTagList = blogATagMapper.selectList(queryWrapper);
        byId.setBlogATagList(blogTagList);
        byId.setTagIds(tagsTool(byId.getBlogATagList()));
        model.addAttribute("blog",byId);
        return "admin/blogs-input";
    }
    //编辑时候处理list-string
    public String tagsTool(List<Blog_Tag> list){
            StringBuilder ids=new StringBuilder();
            boolean flag=false;
            for (Blog_Tag tag : list) {
                if(flag){
                    ids.append(",");
                }else {
                    flag=true;
                }
                ids.append(tag.getTId());
            }
            return ids.toString();
    }
    @Transactional
    @GetMapping("/delete/input")
    public String delete(Long id,RedirectAttributes redirectAttributes){
        blogService.removeById(id);
        LambdaQueryWrapper<Blog_Tag> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog_Tag::getBId,id);
        blogATagMapper.delete(queryWrapper);
        redirectAttributes.addFlashAttribute("message","删除成功！");
        return "redirect:/admin/blog";
    }
}
